import React, { useState, useEffect } from 'react';
import { DatePicker } from 'antd';
import classNames from 'classnames';
import { useSetState } from 'ahooks';
import moment from 'moment';
import _ from 'lodash';
import type { RangePickerProps } from 'antd/lib/date-picker';
import './index.less';

const { RangePicker } = DatePicker;

const dateTypeArr = [
  { label: '年', timeFlag: '1', picker: 'year', format: 'YYYY' },
  { label: '月', timeFlag: '2', picker: 'month', format: 'YYYYMM' },
  { label: '日', timeFlag: '3', picker: 'date', format: 'YYYYMMDD' },
];

const TjDateSelect: React.FC<ITjDateSelectProps> = (props) => {
  const [data, setData] = useSetState<any>(dateTypeArr[0]);
  const [rangePickerValue, setRangePickerValue] = useState<RangePickerProps['value']>();

  const changeDateType = (v: any) => {
    if (props.disabled || v.timeFlag === data.timeFlag || props.disabled) {
      return;
    }
    setData(v);
    const newDate: values = {
      timeFlag: v.timeFlag,
      values:
        v.timeFlag === '3'
          ? [moment().startOf('month'), moment().endOf('month')]
          : [moment(), moment()],
    };

    props.onDateTypeChange && props.onDateTypeChange(newDate);
    props.onChange && props.onChange(newDate);
  };

  const changeRangePicker: RangePickerProps['onChange'] = (date, format) => {
    props.onChange &&
      props.onChange({
        timeFlag: data.timeFlag,
        values: date,
      });
  };

  const onOpenChange = (open: boolean) => {
    props.onOpenChange && props.onOpenChange(open);
  };

  useEffect(() => {
    if (props.value) {
      const timeFlag = _.get(props.value, 'timeFlag', '1');
      const values = _.get(props.value, 'values', undefined);
      const item = _.find(dateTypeArr, (n: any) => n.timeFlag === timeFlag);
      setRangePickerValue(values);
      setData(item);
    }
  }, [props.value]);

  return (
    <div className="tj-date-select">
      <div className="date-type">
        {dateTypeArr.map((v) => {
          return (
            <div
              className={classNames(
                'item',
                { active: data.timeFlag === v.timeFlag },
                { disabled: props.disabled },
              )}
              key={v.timeFlag}
              onClick={() => changeDateType(v)}
            >
              {v.label}
            </div>
          );
        })}
      </div>
      <RangePicker
        picker={data.picker}
        format={data.format}
        onChange={changeRangePicker}
        disabled={props.disabled}
        value={rangePickerValue}
        onOpenChange={onOpenChange}
        separator="-"
      />
    </div>
  );
};

type values = {
  timeFlag: '1' | '2' | '3';
  values: RangePickerProps['value'];
};

interface ITjDateSelectProps {
  value?: any;
  onChange?: (value: values) => void;
  disabled?: boolean;
  onDateTypeChange?: (value: values) => void;
  onOpenChange?: RangePickerProps['onOpenChange'];
}

export { TjDateSelect };
